<template>
  <el-dialog
    :title="title"
    :visible.sync="isVisible"
    :width="width"
    :before-close="handleClose"
    :lock-scroll="true"
    :close-on-click-modal="false"
    custom-class="pub_dialog"
    @open="getData"
  >
    <VForm
      ref="vformComponents"
      :form="formData.form"
      :options="formData.options"
      :rules="formData.rules"
      :labelWidth="formData.labelWidth"
      :rowspan="rowspan"
      @toLoadMethods="toLoadMethods"
    ></VForm>

    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="sure"  v-if="openType!='detail'">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  alarmDeviceDetail,
  alarmDeviceUpdate,
  alarmDeviceAdd
} from '@/api/alarm/device'
import VForm from "@/components/VForm";
import {alarmFacilityTypeList} from "@/api/alarm/alarmFacilityType";
import {
  alarmFacilityDeviceTypeList,
  alarmFacilityDeviceTypeListByFacilityId
} from "@/api/alarm/deviceType";
import {alarmFacilityDeviceItemList} from "@/api/alarm/deviceItem";
import {alarmMonitorPointList} from "@/api/alarm/point";
import {alarmFacilityList} from "@/api/alarm/facility";
import { collectBuildingProjectList } from '@/api/build/project'

export default {
  components: {
    VForm,
  },
  props: {
    width: {
      type: String,
      default: "75%",
    },
    title: {
      type: String,
      default: "详情",
    },
    id: {},
    openType: {
      type: String,
      default: "add"
    },
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    'width': {
      handler(newVal, oldVal) {
        console.log('newVal===', newVal, oldVal)
        let w = this.width.split('%')[0]
        if (w >= 60) {
          this.rowspan = 2
        } else {
          this.rowspan = 1
        }
      },
      deep: true,
      immediate: true
    },
    'modeType': {
      handler(newVal, oldVal) {
        this.formData.form.modeType = newVal;
      },
      deep: true,
      immediate: true
    },
    'typeOptions': {
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'type') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'statusOptions': {
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'status') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'monitorObjectTypeOptions': {
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'monitorObjectType') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'monitorTypeOptions': {
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'monitorType') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'monitorObjectIdOptions': {
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'monitorObjectId') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'openType':{
      handler(newVal, oldVal) {
        this.formData.options = this.formData.options.filter(t=> !t.readonly)
        if(newVal != 'add'){
          // let item = {
          //   title: "标识码",
          //   key: "identificationCode",
          //   type: "text",
          //   disabled: true,
          //   readonly:true
          // }
          // this.formData.options.unshift(item)
        }
        this.formData.options.forEach(t => {
          if(!t.readonly) {
            t.disabled = newVal == 'detail'
          }
        })
        if(newVal=='edit'){
          this.changeDisabled(true)
        }
      },
      deep: true,
      immediate: true
    },
    'buildProjectList':{
      handler(newVal, oldVal) {
        if(newVal){
          this.formData.options.forEach(t=>{
            if(t.key == "buildingId"){
              t.option.data = newVal
            }
          })
        }
      },
      deep: true,
      immediate: true
    },
  },
  computed: {
    isVisible: {
      get() {
        return this.dialogVisible
      },
      set() {
        this.close()
      }
    }
  },
  data() {
    return {
      modeType: '',

      rowspan: 1,
      dict: {},
      formData: {
        form: {
          modeType: this.modeType,
          identificationCode: "",
          name: "",
          type: "",
          facilityTypeId: "",
          deviceCode: "",
          manufacturerName: "",
          equipmentType: "",
          serialNo: "",
          useFor: "",
          installationTime: "",
          equipmentSource: "",
          monitorType: "",
          monitorTypeName: "",
          facilityDeviceTypeId: "",
          collectionFrequency: "",
          uploadFrequency: "",
          powerType: "",
          registerOnlineTime: "",
          status: "",
          netState: "",
          monitorObjectType: "",
          monitorObjectId: "",
          monitorObjectName: "",
          installationAddress: "",
          hazardId: "",
          relativeHeight: "",
          lon: "",
          lat: "",
          provinceCode: "",
          cityCode: "",
          countyCode: "",
          areaCode: "",
          producer: "",
          producerName: "",
          batchNo: "",
          produceAt: "",
          expireAt: "",
          platform: "",
          network: "",
          extendJson: "",
          createUser: "",
          updateTime: "",
          updateUser: "",
        },
        options: [
          // {
          //   title: "标识码",
          //   key: "identificationCode",
          //   type: "text",
          // },
          {
            title: "所属工地",
            key: "buildingId",
            type: "select",
            multiple: false,
            disabled: false,
            option: {
              data: this.buildProjectList,
              props: {
                key: "id", // 指定key对应data的字段
                label: "projectName", // 指定label对应data的字段
                value: "id", // 指定value对应data的字段
              },
            },
          },
          {
            title: "设备名称",
            key: "name",
            type: "text",
          },

          {
            title: "监测对象类型",
            key: "monitorObjectType",
            type: "select",
            multiple: false,
            event: 'changeTypeOptions',
            disabled: false,
            option: {
              data: this.monitorObjectTypeOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "name", // 指定value对应data的字段
              },
            },
          },
          {
            title: "所属监测点",
            key: "monitorObjectId",
            type: "select",
            multiple: false,
            event: 'changePointObject',
            disabled: false,
            option: {
              data: this.monitorObjectIdOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "pointName", // 指定label对应data的字段
                value: "id", // 指定value对应data的字段
              },
            },
          },
          {
            title: "安装位置",
            key: "installationAddress",
            type: "text",
            disabled: true,
            placeholder:"选择点位自动获取"
          },
          {
            title: "设备类型",
            key: "type",
            type: "select",
            multiple: false,
            event: 'changeDeviceType',
            disabled: false,
            option: {
              data: this.typeOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "name", // 指定label对应data的字段
                value: "id", // 指定value对应data的字段
              },
            },
          },
          {
            title: "设备代码",
            key: "deviceCode",
            type: "text",
          },
          {
            title: "设备厂商信息",
            key: "manufacturerName",
            type: "text",
          },
          {
            title: "设备型号",
            key: "equipmentType",
            type: "text",
          },
          {
            title: "安装时间",
            key: "installationTime",
            type: "datetime",
          },
          {
            title: "设备来源",
            key: "equipmentSource",
            type: "text",
          },
          {
            title: "监测项",
            key: "monitorType",
            type: "select",
            multiple: false,
            disabled: false,
            option: {
              data: this.monitorTypeOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "name", // 指定label对应data的字段
                value: "id", // 指定value对应data的字段
              },
            },
          },
          {
            title: "采集频率",
            key: "collectionFrequency",
            type: "text",
          },
          {
            title: "上传频率",
            key: "uploadFrequency",
            type: "text",
          },
          {
            title: "供电方式",
            key: "powerType",
            type: "text",
          },
          {
            title: "注册上线时间",
            key: "registerOnlineTime",
            type: "datetime",
          },
          {
            title: "设备状态",
            key: "status",
            type: "select",
            multiple: false,
            option: {
              data: this.statusOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "value", // 指定value对应data的字段
              },
            },
          },
          {
            title: "相对高度",
            key: "relativeHeight",
            type: "text",
          },
          {
            title: "关联隐患",
            key: "hazardId",
            type: "text",
          },
        ],
        rules: {
          modeType: [
            {required: true, message: '请选择', trigger: 'change'},
          ],
          monitorObjectId: [
            {required: true, message: '请选择', trigger: 'change'},
          ],
          // identificationCode: [
          //   {required: true, message: '请输入', trigger: 'blur'},
          //   {max: 20, message: '长度最大为20个字符', trigger: 'blur'}
          // ],
          name: [
            {required: true, message: '请输入', trigger: 'blur'},
            {max: 128, message: '长度最大为128个字符', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '请选择', trigger: 'change'},
          ],
          deviceCode: [
            {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
          ],
          manufacturerName: [
            {max: 128, message: '长度最大为128个字符', trigger: 'blur'}
          ],
          equipmentType: [],
          serialNo: [
            {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
          ],
          useFor: [],
          installationTime: [],
          equipmentSource: [
            {max: 32, message: '长度最大为32个字符', trigger: 'blur'}
          ],
          monitorType: [
            {required: true, message: '请选择', trigger: 'change'},
          ],
          collectionFrequency: [
            {max: 32, message: '长度最大为32个字符', trigger: 'blur'}
          ],
          uploadFrequency: [
            {max: 32, message: '长度最大为32个字符', trigger: 'blur'}
          ],
          powerType: [],
          registerOnlineTime: [],
          status: [],
          netState: [],
          monitorObjectType: [
            {required: true, message: '请选择', trigger: 'change'},
          ],
          installationAddress: [
            {max: 128, message: '长度最大为128个字符', trigger: 'blur'}
          ],
          hazardId: [
            {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
          ],
          relativeHeight: [
            {max: 32, message: '长度最大为32个字符', trigger: 'blur'}
          ],
          lon: [
            {max: 36, message: '长度最大为36个字符', trigger: 'blur'}
          ],
          lat: [
            {max: 36, message: '长度最大为36个字符', trigger: 'blur'}
          ],
          provinceCode: [
            {max: 12, message: '长度最大为12个字符', trigger: 'blur'}
          ],
          cityCode: [
            {max: 12, message: '长度最大为12个字符', trigger: 'blur'}
          ],
          countyCode: [
            {max: 12, message: '长度最大为12个字符', trigger: 'blur'}
          ],
          areaCode: [
            {max: 12, message: '长度最大为12个字符', trigger: 'blur'}
          ],
          producer: [
            {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
          ],
          producerName: [
            {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
          ],
          batchNo: [
            {max: 32, message: '长度最大为32个字符', trigger: 'blur'}
          ],
          produceAt: [],
          expireAt: [],
          platform: [
            {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
          ],
          network: [
            {max: 16, message: '长度最大为16个字符', trigger: 'blur'}
          ],
          extendJson: [
            {max: 1024, message: '长度最大为1024个字符', trigger: 'blur'}
          ],
          createUser: [
            {max: 36, message: '长度最大为36个字符', trigger: 'blur'}
          ],
          updateTime: [],
          updateUser: [
            {max: 36, message: '长度最大为36个字符', trigger: 'blur'}
          ],
        },
        labelWidth: "140px",
      },
      // 字典
      typeOptions: [],
      equipmentTypeOptions: [],
      monitorTypeOptions: [],
      powerTypeOptions: [],
      statusOptions: [],
      monitorObjectTypeOptions: [],
      monitorObjectIdOptions: [],
      buildProjectList:[]
    };
  },
  methods: {
    toLoadMethods(methods) {
      this[methods]()
    },
    changeDeviceType() {
      //监测项monitorType
      this.monitorTypeOptions = []
      this.formData.form.monitorType = ''

      const deviceId = this.formData.form.type
      console.log('--deviceId--' + deviceId)
      this.getDeviceItem(deviceId)
    },
    getDeviceItem(deviceId) {
      alarmFacilityDeviceItemList({"facilityDeviceTypeId": deviceId}).then(res => {
        if (res.code == 200) {
          this.monitorTypeOptions = res.data
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      })
    },
    changePointObject() {
      //设备类型type
      this.typeOptions = []
      this.formData.form.type = ''
      //监测项monitorType
      this.monitorTypeOptions = []
      this.formData.form.monitorType = ''

      const monitorObjectId = this.formData.form.monitorObjectId;
      let item = this.monitorObjectIdOptions.find(x => x.id == monitorObjectId)
      if (item != undefined) {
        this.formData.form.installationAddress = item.address
        this.changeAddress(item)
        console.log('---facilityId---' + item.facilityId)
        this.getFacilityTypeToDevice(item.facilityId)
      }
    },
    changeAddress(data) {
      console.log('changeAddress', data)
      this.formData.form.lon = data.lon
      this.formData.form.lat = data.lat

      this.formData.form.provinceCode = data.provinceCode
      this.formData.form.cityCode = data.cityCode
      this.formData.form.countyCode = data.countyCode
      this.formData.form.areaCode = data.areaCode
    },
    changeTypeOptions() {
      //设备类型type
      this.typeOptions = []
      this.formData.form.type = ''
      //监测项monitorType
      this.monitorTypeOptions = []
      this.formData.form.monitorType = ''
      //点位名称monitorObjectId
      this.monitorObjectIdOptions = []
      this.formData.form.monitorObjectId = ''
      const jcId = this.formData.form.monitorObjectType;
      if (jcId === '1') {
        this.getMonitorPonitOptions();
      }
    },
    getMonitorPonitOptions() {
      this.monitorObjectIdOptions = [];
      //设备类型
      this.typeOptions = []
      this.getMonitorObjectIdList();
    },
    getMonitorObjectIdList() {

      alarmMonitorPointList({"modeType": this.modeType }).then(res => {
        if (res.code == 200) {
          this.monitorObjectIdOptions = res.data
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      })
    },
    getFacilityTypeToDevice(facilityId) {
      //找设施id
      alarmFacilityList({"id": facilityId}).then(res => {
        if (res.code == 200) {
          this.getDeviceList(res.data[0].facilityId);
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      })
    },
    getDeviceList(facilityId) {
      console.log('---facilityId--' + facilityId)
      alarmFacilityDeviceTypeList({"facilityTypeId": facilityId}).then(res => {
        if (res.code == 200) {
          this.typeOptions = res.data
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      })
    },
    getMonitorTypeOptions(facilityDeviceTypeId) {
      alarmFacilityDeviceItemList({"facilityDeviceTypeId": facilityDeviceTypeId}).then(res => {
        if (res.code == 200) {
          this.monitorTypeOptions = res.data
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      });
    },
    submitFormat() {
    },
    loadFormat() {
    },
    getCheckBoxData(value, option, type) {
      if (type == "submit") {
        if (value.length == 0) {
          return null
        }
        let temp = [];
        value.forEach(t => {
          let item = option.find(x => x.label == t)
          if (item != undefined) {
            temp.push(item.value)
          }
        })
        return temp.join(",")
      } else {
        if (!value) {
          return []
        } else {
          let data = value.split(",")
          let temp = []
          data.forEach(t => {
            let item = option.find(x => x.value == t)
            if (item != undefined) {
              temp.push(item.label)
            }
          })
          return temp
        }
      }
    },
    sure() {
      // this.formData.form.identificationCode="1"
      console.log('sure===', this.formData.form)
      this.$refs.vformComponents.$refs.form.validate().then(res => {
        this.submitFormat()
        if (this.openType == "add") {
          this.add()
        } else {
          this.update()
        }
      })
    },
    add() {
      this.formData.form.id = null
      alarmDeviceAdd(this.formData.form).then(res => {
        if (res.code == 200) {
          this.$message({
            message: this.$t('tips.createSuccess'),
            type: 'success'
          })
          this.closeSuccess()
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      })
    },
    update() {
      alarmDeviceUpdate(this.formData.form).then(res => {
        if (res.code == 200) {
          this.$message({
            message: this.$t('tips.updateSuccess'),
            type: 'success'
          })
          this.closeSuccess()
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      })
    },
    cancel() {
      this.close()
    },
    handleClose(done) {
      done()
      this.close()
    },
    closeSuccess() {
      this.$refs.vformComponents.$refs.form.resetFields();
      this.$emit('success')
    },
    close() {
      this.$refs.vformComponents.$refs.form.resetFields();
      this.$emit('close')
    },
    getBuildProjectList(){
      collectBuildingProjectList().then(res=>{
        if(res.code==200){
          this.buildProjectList = res.data
        }
      })
    },
    getData() {
      this.getBuildProjectList()
      if (this.openType != "add") {
        alarmDeviceDetail(this.id).then(res => {
          if (res.code == 200) {
            this.selectTypeInit(res);
            this.formData.form = res.data
            // this.changeDisabled(true);
            this.loadFormat()
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })

        return;
      }
      //add
      // this.changeDisabled(false);
    },
    changeDisabled(value) {
      this.formData.options.find(t => t.key == 'monitorObjectType').disabled = value;
      this.formData.options.find(t => t.key == 'monitorObjectId').disabled = value;
      this.formData.options.find(t => t.key == 'type').disabled = value;
      this.formData.options.find(t => t.key == 'monitorType').disabled = value;
    },
    selectTypeInit(res) {
      //点位
      res.data.monitorObjectId = parseInt(res.data.monitorObjectId)
      this.getMonitorObjectIdList();
      //设备类型
      res.data.type = parseInt(res.data.type)
      this.getDeviceList(res.data.facilityTypeId);
      //监测项,先找设备然后找facilityDeviceTypeId
      res.data.monitorType = parseInt(res.data.monitorType)
      this.getDeviceItem(res.data.facilityDeviceTypeId);
    },
    initAlarmConfig() {
      let type = this.$route.path
      console.log("path:" + type)
      const config = this.$commonJs.getAlarmPathConfig(this.$route.path)
      this.modeType = config.modeType
    }
  },
  created() {
    this.initAlarmConfig()
    // 获取字典值
    this.statusOptions = []
    this.$commonJs.filterDataDict("alarmDeviceStatus", this.statusOptions)

    this.monitorObjectTypeOptions = []
    this.$commonJs.filterDataDict("alarmDeviceObject", this.monitorObjectTypeOptions)

  }
};
</script>

<style lang="scss" scoped>

</style>
